package com.qulai.amazon_us.service.ebay;


import com.qulai.common.config.EbayConfig;
import com.qulai.amazon_us.domain.ebay.TokenResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Base64;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;

import org.springframework.web.util.UriComponentsBuilder;


@Service
public class EbayAuthService {

    private final EbayConfig ebayConfig;
    private final RestTemplate restTemplate;

    // 存储状态令牌，防止CSRF攻击
    private final Map<String, String> stateStore = new HashMap<>();

    @Autowired
    public EbayAuthService(EbayConfig ebayConfig, RestTemplate restTemplate) {
        this.ebayConfig = ebayConfig;
        this.restTemplate = restTemplate;
    }

    /**
     * 生成授权URL
     */
    public String generateAuthorizationUrl() {
        // 生成唯一的state令牌
        String state = UUID.randomUUID().toString();
        stateStore.put(state, state);

        return UriComponentsBuilder.fromHttpUrl(ebayConfig.getAuthUrl())
                .queryParam("client_id", ebayConfig.getClientId())
                .queryParam("redirect_uri", ebayConfig.getRedirectUri())
                .queryParam("response_type", "code")
                .queryParam("scope", ebayConfig.getScopes())
                .queryParam("state", state)
                .build().toUriString();
    }

    /**
     * 使用授权码获取访问令牌
     */
    public TokenResponse exchangeCodeForToken(String authorizationCode) {
        // 验证state令牌
//        if (!stateStore.containsKey(state)) {
//            throw new SecurityException("Invalid state token");
//        }
//        stateStore.remove(state); // 使用后移除

        // 准备请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 准备Basic Auth凭证
        String credentials = ebayConfig.getClientId() + ":" + ebayConfig.getClientSecret();
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
        headers.set("Authorization", "Basic " + encodedCredentials);

        // 准备请求体
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type", "authorization_code");
        body.add("code", authorizationCode);
        body.add("redirect_uri", ebayConfig.getRedirectUri());

        // 创建HTTP实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        // 发送请求到eBay API
        ResponseEntity<TokenResponse> response = restTemplate.exchange(
                ebayConfig.getTokenUrl(),
                HttpMethod.POST,
                requestEntity,
                TokenResponse.class
        );

        return response.getBody();
    }

    /**
     * 使用刷新令牌获取新访问令牌
     */
    public TokenResponse refreshAccessToken(String refreshToken) {
        // 准备请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // 准备Basic Auth凭证
        String credentials = ebayConfig.getClientId() + ":" + ebayConfig.getClientSecret();
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
        headers.set("Authorization", "Basic " + encodedCredentials);

        // 准备请求体
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type", "refresh_token");
        body.add("refresh_token", refreshToken);
        body.add("scope", ebayConfig.getScopes());

        // 创建HTTP实体
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(body, headers);

        // 发送请求
        ResponseEntity<TokenResponse> response = restTemplate.exchange(
                ebayConfig.getTokenUrl(),
                HttpMethod.POST,
                requestEntity,
                TokenResponse.class
        );

        return response.getBody();
    }
}